import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

/// 搜索历史服务类
class SearchHistoryService extends GetxService {
  // 存储实例
  late final GetStorage _storage;

  // 存储key常量
  static const String _keySearchHistory = 'search_history';

  // 最大历史记录数量
  static const int _maxHistoryCount = 10;

  @override
  void onInit() {
    super.onInit();
    _storage = GetStorage();
  }

  /// 获取搜索历史记录
  List<String> getSearchHistory() {
    try {
      final historyData = _storage.read(_keySearchHistory);
      if (historyData is List) {
        return historyData.cast<String>();
      }
      return [];
    } catch (e) {
      print('获取搜索历史失败: $e');
      return [];
    }
  }

  /// 添加搜索记录
  Future<void> addSearchHistory(String keyword) async {
    if (keyword.trim().isEmpty) return;

    try {
      final history = getSearchHistory();

      // 如果已存在，先移除
      history.remove(keyword.trim());

      // 添加到列表头部
      history.insert(0, keyword.trim());

      // 限制历史记录数量
      if (history.length > _maxHistoryCount) {
        history.removeRange(_maxHistoryCount, history.length);
      }

      // 保存到本地存储
      await _storage.write(_keySearchHistory, history);
      print('搜索历史已保存: $keyword');
    } catch (e) {
      print('保存搜索历史失败: $e');
    }
  }

  /// 删除单个搜索记录
  Future<void> removeSearchHistory(String keyword) async {
    try {
      final history = getSearchHistory();
      history.remove(keyword);
      await _storage.write(_keySearchHistory, history);
      print('搜索历史已删除: $keyword');
    } catch (e) {
      print('删除搜索历史失败: $e');
    }
  }

  /// 清空所有搜索历史
  Future<void> clearSearchHistory() async {
    try {
      await _storage.remove(_keySearchHistory);
      print('搜索历史已清空');
    } catch (e) {
      print('清空搜索历史失败: $e');
    }
  }

  /// 检查是否有搜索历史
  bool hasSearchHistory() {
    return getSearchHistory().isNotEmpty;
  }
}
